// Copyright 2016-2022 The Libsacloud Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"log"
	"path/filepath"

	"github.com/sacloud/libsacloud/v2/internal/define"
	"github.com/sacloud/libsacloud/v2/internal/dsl"
	"github.com/sacloud/libsacloud/v2/internal/tools"
)

const destination = "sacloud/fake/zz_store.go"

func init() {
	log.SetFlags(0)
	log.SetPrefix("gen-api-fake-store: ")
}

func main() {
	dsl.IsOutOfSacloudPackage = true

	tools.WriteFileWithTemplate(&tools.TemplateConfig{
		OutputPath: filepath.Join(tools.ProjectRootPath(), destination),
		Template:   tmpl,
		Parameter:  define.APIs,
	})
	log.Printf("generated: %s\n", filepath.Join(destination))
}

const tmpl = `// generated by 'github.com/sacloud/libsacloud/internal/tools/gen-fake-store'; DO NOT EDIT

package fake

import (
	"github.com/sacloud/libsacloud/v2/sacloud"
	"github.com/sacloud/libsacloud/v2/sacloud/types"
	"github.com/sacloud/libsacloud/v2/sacloud/accessor"
)

{{ range . }} 
func get{{.TypeName}}(zone string) []*sacloud.{{.TypeName}} {
	values := ds().List(Resource{{.TypeName}}, zone)
	var ret []*sacloud.{{.TypeName}}
	for _ , v := range values {
		if v, ok := v.(*sacloud.{{.TypeName}}); ok {
			ret = append(ret, v)
		}
	}
	return ret
}

func get{{.TypeName}}ByID(zone string, id types.ID) *sacloud.{{.TypeName}} {
	v := ds().Get(Resource{{.TypeName}}, zone, id)
	if v, ok := v.(*sacloud.{{.TypeName}}); ok {
		return v
	}
	return nil
}

func put{{.TypeName}}(zone string, value *sacloud.{{.TypeName}}) {
	var v interface{} = value
	if id, ok := v.(accessor.ID); ok {
		ds().Put(Resource{{.TypeName}}, zone, id.GetID(), value)
		return
	}
	ds().Put(Resource{{.TypeName}}, zone, 0, value)
}
{{ end }}
`
